package com.soft.zzti.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.soft.zzti.entity.ResponseJsonBean;
import com.soft.zzti.util.EmailUtil;

/**
 * 发送邮件
 * @author hucl
 *
 */
@Controller
public class EmailController {
	//日志
    private static Logger log = LoggerFactory.getLogger(EmailController.class);
    /**
     * 给用户发送验证码
     * @param email
     * @param session
     * @return
     * @throws Exception
     */
	@RequestMapping(value="/sendEmail",method= {RequestMethod.POST})
	public @ResponseBody ResponseJsonBean sendEmailToUser(String email, HttpSession session) throws Exception{
		ResponseJsonBean responseJsonBean = new ResponseJsonBean();
		Map<String, Object> result = new HashMap<>();
		//获取随机四位验证码
		String code = EmailUtil.getRandomCode();
		String message = "您的验证码是："+code+",请尽快填写，谢谢合作";
		String subject = "找回密码功能验证码邮件";
		//保存到session中
		session.setAttribute("emailCode", code);
		//设置最大存活时间1分钟 单位秒
		session.setMaxInactiveInterval(60);
		//发送邮件
		try {
			EmailUtil.sendEmail(email, subject, message);
			responseJsonBean.setMsgFlag("0");
			responseJsonBean.setResultJson(result);
		} catch (Exception e) {
			log.debug(e.getMessage());
			responseJsonBean.setMsgFlag("1");
			responseJsonBean.setErrorMsg(e.getMessage());
			responseJsonBean.setResultJson(result);
			e.printStackTrace();
		}
		
		return responseJsonBean;
	}
	/**
	 * 邮箱验证码校验
	 * @return
	 */
	@RequestMapping(value="/emailCodeCheck",method= {RequestMethod.POST})
	public @ResponseBody ResponseJsonBean verificationCodeCheck(String verificationCode, HttpSession session) {
		ResponseJsonBean responseJsonBean = new ResponseJsonBean();
		Map<String, Object> result = new HashMap<>();
		String emailCode = (String) session.getAttribute("emailCode");
		if(verificationCode.equals(emailCode)) {
			responseJsonBean.setMsgFlag("0");
			responseJsonBean.setResultJson(result);
		}else {
			responseJsonBean.setMsgFlag("1");
			responseJsonBean.setResultJson(result);
			responseJsonBean.setErrorMsg("验证码不正确，请重新输入");
		}
		return responseJsonBean;
	}

}
